<script setup>
import {
  artEditArticlesService,
  artGetDetailsService,
  artLaunchArticlesService
} from '@/api/article'
import { imageUrlToFile } from '@/utils/format'
import { baseURL } from '@/utils/request'
import { Plus } from '@element-plus/icons-vue'
// 注册局部组件
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'
const showDrawer = ref(false)
const emit = defineEmits('success')
const addOrEdit = ref('')
// 定义一个方法，暴露抽屉状态，接收参数
// 如果参数为{},则为添加。如果参数为对象，则为编辑
const openDrawer = async (row) => {
  showDrawer.value = true
  if (row.id) {
    // 编辑操作
    addOrEdit.value = '编辑文章'
    // 编辑文章回显
    const res = await artGetDetailsService(row.id)
    formModel.value = res.data.data
    // imageUrl 需要单独(接口注意：cover_img 的值, 需要自己拼接服务器前缀地址, 和接口服务的基地址相同)
    imageUrl.value = baseURL + formModel.value.cover_img
    // 更新接口中 cover_img 为一个 file对象，因此要将 string 转化为 file 对象
    formModel.value.cover_img = await imageUrlToFile(
      imageUrl.value,
      formModel.value.cover_img
    )
  } else {
    // 需手动重置上传图片和富文本编辑
    imageUrl.value = ''
    editorRef.value.setHTML('')
    // 添加操作
    addOrEdit.value = '添加文章'
    formModel.value = { ...defaultForm }
  }
}

const width = ref('100%')
// 表单数据
const defaultForm = {
  title: '',
  cate_id: '',
  content: '',
  cover_img: '',
  state: ''
}
const formModel = ref({ ...defaultForm })

const imageUrl = ref('')
const editorRef = ref()
const onUploadFile = (uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

const onLaunch = async (state) => {
  // 存入发布状态
  formModel.value.state = state
  // 因为数据中含有图片，需要传入 formData 对象
  const formData = new FormData()
  for (let key in formModel.value) {
    formData.append(key, formModel.value[key])
  }
  if (addOrEdit.value === '编辑文章') {
    // 执行编辑操作
    await artEditArticlesService(formData)
    ElMessage.success('编辑成功')
    showDrawer.value = false
    // 传达父级发布成功
    emit('success', 'edit')
  } else {
    // 执行发布操作
    await artLaunchArticlesService(formData)
    ElMessage.success('发布成功')
    showDrawer.value = false
    // 传达父级发布成功
    emit('success', 'add')
  }
}

defineExpose({
  openDrawer
})
</script>

<template>
  <el-drawer v-model="showDrawer" :title="addOrEdit" size="40%">
    <el-form :model="formModel" :rules="rules" ref="formRef">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-select
          v-model="formModel.cate_id"
          :width="width"
        ></channel-select>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 此处不用 action 请求上传，在提交之前只需要展示图片
         auto-file：false 关闭自动上传文件
         on-change: 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用 -->
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onUploadFile"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <QuillEditor
            theme="snow"
            v-model:content="formModel.content"
            contentType="html"
            ref="editorRef"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLaunch('已发布')">发布</el-button>
        <el-button type="info" @click="onLaunch('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
